package promotion.resource;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import org.restlet.data.Status;
import org.restlet.ext.xml.DomRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.Get;
import org.restlet.resource.ResourceException;
import org.restlet.resource.ServerResource;
import org.w3c.dom.Document;
import promotion.db.DataSourceFactory;
import promotion.db.Database;
import promotion.model.*;
import promotion.model.Telephone;
import promotion.model.Type;
import promotion.rest.Serveur;
import promotion.validator.LongRangeValidator;

/**
 * Resource permettant de récupérer un flux xml représentant une promotion
 * @author marya
 */
public class PromotionResource extends ServerResource {

    private List<ResourceError> errors;
    private Database database;
    private Promotion promotion;

    public PromotionResource() {
        super();
        this.database = Serveur.getDatabase();
        this.errors = new ArrayList<ResourceError>();
    }

    /**
     * Initialisation de la promotion
     * @throws ResourceException
     */
    @Override
    protected void doInit() throws ResourceException {
        Long idPromotion;
        final String sqlPromotion = "SELECT id_promotion,nom FROM promotion WHERE id_promotion = ";
        final String sqlEtudiant = "SELECT etudiant.id_etudiant, etudiant.nom, etudiant.prenom, "
                + "etudiant.voie, etudiant.ville, "
                + "etudiant.code_postal, etudiant.pays "
                + "FROM etudiant_promotion "
                + "INNER JOIN promotion ON "
                + "etudiant_promotion.id_promotion = promotion.id_promotion "
                + "INNER JOIN etudiant ON "
                + "etudiant.id_etudiant = etudiant_promotion.id_etudiant "
                + "WHERE etudiant_promotion.id_promotion = ";

        final String sqlTel = "SELECT tel.value, type.libelle FROM tel "
                + "INNER JOIN type ON type.id_type = tel.id_type "
                + "WHERE tel.id_etudiant = ";
        final String sqlEmail = "SELECT email.value, type.libelle FROM email "
                + "INNER JOIN type ON type.id_type = email.id_type "
                + "WHERE email.id_etudiant = ";

        String idPromotionAttribute = getRequest().getAttributes().get("idPromotion").toString();
        LongRangeValidator longRangeValidator = new LongRangeValidator(1l, null);

        //Validation de l'id de la promotion
        if (longRangeValidator.isValid(idPromotionAttribute)) {
            idPromotion = Long.parseLong(idPromotionAttribute);
        } else {
            errors.add(new ResourceError("invalidPromotion"));
            throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST);
        }

        try {

            Connection connexion = database.getNewConnection();
            Statement statement = connexion.createStatement();
            ResultSet rsPromotion = statement.executeQuery(sqlPromotion + idPromotion);
            if (rsPromotion.next()) {
                promotion = new Promotion(rsPromotion.getInt("id_promotion"), rsPromotion.getString("nom"));
            } else {
                throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND);
            }

            ResultSet rsEtudiant = statement.executeQuery(sqlEtudiant + idPromotion);
            ResultSet rsTel = null;
            ResultSet rsEmail = null;

            while (rsEtudiant.next()) {
                int idEtudiant = rsEtudiant.getInt("id_etudiant");
                System.out.println(idEtudiant);
                Etudiant e = new Etudiant(
                        rsEtudiant.getString("nom"),
                        rsEtudiant.getString("prenom"),
                        new Adresse(rsEtudiant.getString("voie"),
                        rsEtudiant.getString("ville"),
                        rsEtudiant.getString("code_postal"),
                        rsEtudiant.getString("pays")));
                rsTel = connexion.createStatement().executeQuery(sqlTel + idEtudiant);
                while (rsTel.next()) {
                    e.getTels().add(new Telephone(Type.getType(rsTel.getString("libelle")), rsTel.getString("value")));
                }
                rsEmail = connexion.createStatement().executeQuery(sqlEmail + idEtudiant);
                while (rsEmail.next()) {
                    e.getEmails().add(new Email(Type.getType(rsEmail.getString("libelle")), rsEmail.getString("value")));
                }
                promotion.getEtudiants().add(e);
            }

            
            promotion.setUrl(getRootRef().getHostIdentifier() + "/promotions/" + promotion.getIdPromotion());
            connexion.close();
        } catch (SQLException e) {
            throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e);
        }
    }

    @Get
    public Representation doGet() throws Exception {
        return promotion.toXML();
    }
}
